package mediaplayermanager;

import java.util.Hashtable;

import org.knopflerfish.service.log.LogRef;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;

public class Activator implements BundleActivator, EventHandler   
{
	private static final String NEW_MEDIA_SET_ARRIVED = "newMediaSet";
	private ServiceRegistration serviceRegistration;
	public static BundleContext bc = null;
	private  LogRef log;
	private MPlayerManagerConfig config;
	private MPlayerManagerThread mPlayerManagerThread;
	protected static Object waitObject = new Object();
	
	public void start(BundleContext bc) throws Exception 
	{
		Activator.bc = bc;
		log = new LogRef(bc);
		try
		{
			config = MPlayerManagerConfig.getConfig();
		}
		catch(Exception e)
		{
			log.error(Activator.bc.getBundle().getHeaders().get(Constants.BUNDLE_NAME)+ " failed to start due to configuration file setup error.");
			System.err.println(Activator.bc.getBundle().getHeaders().get(Constants.BUNDLE_NAME)+ " failed to start due to configuration file setup error.");
			Activator.bc = null;
			throw e;
		}
		Hashtable ht = new Hashtable();
		String[] eventToListen = {NEW_MEDIA_SET_ARRIVED};
		ht.put(EventConstants.EVENT_TOPIC, eventToListen);
		serviceRegistration = bc.registerService(EventHandler.class.getName(), this, ht);
		mPlayerManagerThread = new MPlayerManagerThread();
		mPlayerManagerThread.start();
		mPlayerManagerThread.setName("MPlayerManagerThread");
		System.out.println(bc.getBundle().getHeaders().get(Constants.BUNDLE_NAME)+ " started...");
	}

	public synchronized void handleEvent(Event event) 
	{
		String eventTopic = event.getTopic();
		if (eventTopic.equals(NEW_MEDIA_SET_ARRIVED))
		{
			mPlayerManagerThread.loopTillNextTriggerFlag = "T";
			mPlayerManagerThread.playCurrentMediaSet = false;
			synchronized(waitObject)
			{
				waitObject.notifyAll();
			}
			System.out.println("Notified MediaPlayer Manager Thread about arrival of new media set");
		}
	}
	
	public void stop(BundleContext context) throws Exception 
	{
		mPlayerManagerThread.stopThread();
		if (serviceRegistration!=null)
		{
			serviceRegistration.unregister();
			serviceRegistration = null;
		}
		System.out.println(bc.getBundle().getHeaders().get(Constants.BUNDLE_NAME)+ " stopped!");
		Activator.bc = null;
	}
}
